let { projectRootPath } = require("../../util/path/index.js");
let {
  executeSql,
  transaction,
  getTotal,
  getByPagination,
  removeByUuid,
  getAll,
} = require(`${projectRootPath}/mysql/index.js`);
let { getUuid } = require(`${projectRootPath}/util/uuid/index.js`);
let { getCurrentDatetime } = require(
  `${projectRootPath}/util/datetime/index.js`,
);
let { getTaskByAll, removeTaskByUuid } = require(
  `${projectRootPath}/service/task/index.js`,
);

// 创建员工
async function createUser(data) {
  let { name, avatar, username, password, roleUuidList } = data;
  return await transaction(async (connection) => {
    let sql = `insert into UserTable (uuid, name, avatar, username, password, roleUuidList, token, opDatetime) 
                values ('${getUuid()}', '${name}', '${avatar}', '${username}', '${password}', '${roleUuidList}', '', '${getCurrentDatetime()}')`;
    await executeSql(connection, sql);
  });
}
// 获取员工分页数据
async function getUserByPagination(data) {
  let { pageSize, currentPage, name } = data;
  let where = "";
  if (name) {
    where = `where name like '%${name}%'`;
  }
  return await transaction(async (connection) => {
    let list = await getByPagination(
      connection,
      "UserTable",
      "opDatetime",
      where,
      pageSize,
      currentPage,
    );
    let total = await getTotal(connection, "UserTable", "opDatetime", where);
    return { list, total };
  });
}
// 通过 uuid 编辑用户
async function editUserByUuid(data) {
  let { uuid, name, roleUuidList, avatar, username, password, token } = data;
  return await transaction(async (connection) => {
    let sql = `update UserTable set name='${name}', roleUuidList='${roleUuidList}', avatar='${avatar}', username='${username}',
                            password='${password}', token='${token ?? ""}' where uuid='${uuid}'`;
    await executeSql(connection, sql);
  });
}
// 通过 uuid 删除用户
async function removeUserByUuid(data) {
  let { uuid } = data;
  return await transaction(async (connection) => {
    await removeByUuid(connection, "UserTable", uuid);
    let sql = `delete from TaskTable where userUuid='${uuid}'`;
    await executeSql(connection, sql);
    sql = `delete from NoteTable where userUuid='${uuid}'`;
    await executeSql(connection, sql);
    sql = `delete from PatrolTable where userUuid='${uuid}'`;
    await executeSql(connection, sql);
  });
}

// 获取全部用户
async function getUserByAll() {
  return await transaction(async (connection) => {
    let list = await getAll(connection, "UserTable", "opDatetime");
    return { list };
  });
}

// 通过用户名获取用户信息
async function getUserByUsername(data) {
  let { username } = data;
  return await transaction(async (connection) => {
    let sql = `select * from UserTable where username='${username}'`;
    let list = await executeSql(connection, sql);
    return { list };
  });
}

module.exports = {
  createUser,
  getUserByPagination,
  editUserByUuid,
  removeUserByUuid,
  getUserByAll,
  getUserByUsername,
};
